package com.wjjun.base.utils

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.wjjun.base.ui.viewmodel.BaseWindowViewModel
import java.lang.reflect.ParameterizedType

/**
 *
 * author : wangjunjun
 * date   : 2022/6/9
 * desc   :
 */
class ViewModelFactory {

    companion object Factory {

        /**
         * 创建ViewModel
         */
        fun <VM : BaseWindowViewModel> createViewModel(
            owner: ViewModelStoreOwner,
            cls: Class<*>,
            defCls: Class<out ViewModel>
        ): VM {
            return ViewModelProvider(owner).get(getViewModelClass(cls, defCls)) as VM
        }

        /**
         * 创建ViewModel
         */
        fun <VM : BaseWindowViewModel> createNewViewModel(
            owner: ViewModelStoreOwner,
            cls: Class<*>,
            defCls: Class<out ViewModel>
        ): VM {
            val key = System.currentTimeMillis().toString().plus(":").plus(cls.canonicalName)
            return ViewModelProvider(owner).get(key, getViewModelClass(cls, defCls)) as VM
        }

        /**
         * 获取ViewModel的class类，用于从ViewModelProvider获取ViewModel
         */
        fun getViewModelClass(
            cls: Class<*>,
            defCls: Class<out ViewModel>
        ): Class<out ViewModel> {
            if (cls == defCls) {
                return defCls
            }
            if (cls.genericSuperclass is ParameterizedType) { //当前类没有vm类型
                val types = (cls.genericSuperclass as ParameterizedType).actualTypeArguments
                for (type in types) {
                    if (type.toString().contains("ViewModel")) {
                        return type as Class<out ViewModel>
                    }
                }
            }
            return getViewModelClass(javaClass.superclass, defCls)
        }
    }
}